﻿namespace YunQue.WebApi.Extensions
{
    /// <summary>
    /// 拦截器扩展
    /// </summary>
    public static class FilterExtension
    {
        /// <summary>
        /// 添加拦截器配置
        /// </summary>
        /// <param name="service"></param>
        /// <returns></returns>
        public static IServiceCollection AddFilterConfig(this IServiceCollection service)
        {
            service.AddControllers(options =>
            {
                options.Conventions.Add(new LowerCaseControllerNameConvention());
                options.Filters.Add<RequestAsyncFilter>();
                options.Filters.Add<ResultAsyncFilter>();
            });
            return service;
        }
    }
    /// <summary>
    /// 格式化api接口生成的路由
    /// </summary>
    public class LowerCaseControllerNameConvention : IApplicationModelConvention
    {
        /// <summary>
        /// 格式化路由模板
        /// </summary>
        /// <param name="application"></param>
        public void Apply(ApplicationModel application)
        {
            foreach (var controller in application.Controllers)
            {
                // 将控制器名称的首字母转换为小写
                var controllerName = controller.ControllerName;
                controller.ControllerName = char.ToLowerInvariant(controllerName[0]) + controllerName.Substring(1);
                // 修改路由模板
                foreach (var selector in controller.Selectors)
                {
                    if (selector.AttributeRouteModel != null)
                    {
                        selector.AttributeRouteModel.Template = selector.AttributeRouteModel.Template.Replace("[controller]", controller.ControllerName);
                    }
                }
            }
        }
    }
}
